import os
import configparser
import schedule
import time
import random
from datetime import datetime
import json
from openai import OpenAI
import requests
import pandas as pd
import numpy as np
#import yfinance as yf  # 免费金融数据API
import akshare as ak

# 配置文件路径
CONFIG_FILE = "config.ini"

# ====================== 配置管理类 ======================
class ConfigManager:
    def __init__(self):
        self.config = configparser.ConfigParser()
        self.config.read(CONFIG_FILE)
        
        # 如果配置文件不存在，创建默认配置
        if not os.path.exists(CONFIG_FILE):
            #self.create_default_config()
            print('请创建配置文件！')
            return -1
    
    def create_default_config(self):
        """创建默认配置文件"""
        self.config['DEEPSEEK'] = {
            'api_key': 'your_deepseek_api_key_here',
            'base_url': 'https://api.deepseek.com'
        }
        
        self.config['SETTINGS'] = {
            'portfolio_file': 'portfolio.txt',
            'plan_file': 'operation_plan.json',
            'log_file': 'operation_log.txt',
            'targets_file': 'investment_targets.txt',  # 新增投资目标文件
            'plan_update_day': 'monday',
            'daily_check_time': '14:50',
            'cache_expire_hours': '336',  # 14天（336小时）
            'model': 'deepseek-chat',
            'temperature': '0.3',
            'alpha_vantage_key': 'your_alpha_vantage_key'  # 金融API密钥
        }
        
        with open(CONFIG_FILE, 'w') as f:
            self.config.write(f)
        
        print(f"已创建默认配置文件: {CONFIG_FILE}")
    
    def get(self, section, key):
        """获取配置值"""
        return self.config.get(section, key)
    
    def getfloat(self, section, key):
        """获取浮点数配置值"""
        return self.config.getfloat(section, key)
    
    def getint(self, section, key):
        """获取整数配置值"""
        return self.config.getint(section, key)
    
    def get_deepseek_config(self):
        """获取DeepSeek API配置"""
        return {
            'api_key': self.get('DEEPSEEK', 'api_key'),
            'base_url': self.get('DEEPSEEK', 'base_url')
        }
    
    def get_settings(self):
        """获取系统设置"""
        return {
            'portfolio_file': self.get('SETTINGS', 'portfolio_file'),
            'plan_file': self.get('SETTINGS', 'plan_file'),
            'log_file': self.get('SETTINGS', 'log_file'),
            'targets_file': self.get('SETTINGS', 'targets_file'),  # 投资目标文件
            'plan_update_day': self.get('SETTINGS', 'plan_update_day'),
            'daily_check_time': self.get('SETTINGS', 'daily_check_time'),
            'cache_expire_hours': self.getint('SETTINGS', 'cache_expire_hours'),
            'model': self.get('SETTINGS', 'model'),
            'temperature': self.getfloat('SETTINGS', 'temperature')
        }

# ====================== 持仓管理类 ======================
class PortfolioManager:
    def __init__(self, settings):
        self.settings = settings
        self.portfolio = self.load_portfolio()

    def fresh_portfolio(self):
        self.portfolio = self.load_portfolio()
    
    def load_portfolio(self):
        """从文件加载持仓信息"""
        portfolio = []
        if not os.path.exists(self.settings['portfolio_file']):
            # 创建示例持仓文件
            self.create_sample_portfolio()
            
        with open(self.settings['portfolio_file'], 'r') as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('#'):
                    continue
                parts = line.split(',')
                if len(parts) >= 4:
                    portfolio.append({
                        '基金代码': parts[0],
                        '基金名称': parts[1],
                        '持仓比例': float(parts[2]),
                        '当前收益率': float(parts[3])
                    })
        return portfolio
    
    def create_sample_portfolio(self):
        """创建示例持仓文件"""
        sample_content = """# 基金代码,基金名称,持仓比例(%),当前收益率(%)
008593,天弘沪深300指数增强C,0,0"""
        
        with open(self.settings['portfolio_file'], 'w') as f:
            f.write(sample_content)
        print(f"已创建示例持仓文件: {self.settings['portfolio_file']}")
    
    def get_portfolio_text(self):
        """将持仓信息转换为文本格式"""
        text = "当前持仓情况(每一行分别为基金代码，基金名称，持仓比例，当前收益率):\n"
        for fund in self.portfolio:
            text += f"{fund['基金代码']} {fund['基金名称']} {fund['持仓比例']}% {fund['当前收益率']}%\n"
        return text
    
    def get_fund_current_percent(self, fund_code):
        """获取基金当前持仓比例"""
        for fund in self.portfolio:
            if fund['基金代码'] == fund_code:
                return fund['持仓比例']
        return 0
    
    def get_portfolio_summary(self):
        """获取持仓摘要信息"""
        total_percent = sum(fund['持仓比例'] for fund in self.portfolio)
        return {
            "total_position": {"current": total_percent, "fund_num": len(self.portfolio)},
            "funds": [{"fund_code": f["基金代码"], "current_percent": f["持仓比例"]} for f in self.portfolio]
        }

# ====================== 操作计划更新类 ======================
class PlanUpdater:
    def __init__(self, config_manager):
        self.config_manager = config_manager
        self.settings = config_manager.get_settings()
        self.deepseek_config = config_manager.get_deepseek_config()
        
        # 初始化DeepSeek客户端
        self.client = OpenAI(
            api_key=self.deepseek_config['api_key'],
            base_url=self.deepseek_config['base_url'] + "/v1"
        )
        
        # 持仓管理器
        self.portfolio_manager = PortfolioManager(self.settings)
    
    def get_investment_targets(self):
        """从文件读取投资目标"""
        targets = []
        targets_file = self.settings['targets_file']
        
        if not os.path.exists(targets_file):
            # 创建默认投资目标文件
            default_targets = """# 投资目标文件
投资目标：
1. 争取中短期（1-2年）收益最大化。"""
            
            with open(targets_file, 'w') as f:
                f.write(default_targets)
            print(f"已创建默认投资目标文件: {targets_file}")
        
        with open(targets_file, 'r') as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#'):
                    targets.append(line)
        
        return "\n".join(targets)
    
    def get_deepseek_operation_plan(self):
        """使用DeepSeek Chat API获取操作计划表"""
        # 构建系统提示 - 强调市场环境和仓位调整
        system_prompt = """你是一名专业的理财专家，专注于基金持仓优化和资产配置。请严格遵循以下指令：

1.  **数据驱动：** 综合用户持仓、投资目标，并**实时获取最新的全球主要市场指数、板块行情、宏观经济数据**，作为所有建议的核心依据。
2.  **输出格式：** **必须**以纯净的JSON格式输出，结构如下：
{
    "plan_date": "YYYY-MM-DD",
    "operation_plan": {
        "total_position": {
            "current": [当前总仓位比例],
            "target": [目标总仓位比例],
            "reason": "[调整理由，关联市场数据]"
        },
        "funds": [
            {
                "fund_code": "[代码]",
                "fund_name": "[名称]",
                "current_percent": [当前占比],
                "target_percent": [目标占比],
                "priority": "高/中/低",
                "action": "加仓/减仓/维持",
                "step_percent": [每次调整比例],
                "trigger_conditions": "[具体量化条件，如：沪深300 PE<12 && PE分位数<30% || 纳斯达克100指数回撤>5%]",
                "time_window": "[时间窗口，如：2周内]",
                "reason": "[操作理由，关联行业趋势和技术指标]"
            }
        ],
        "market_analysis": "[简洁的市场分析总结，注明关键数据来源如指数点位和估值]"
    }
}
3.  **建议要求：** 所有操作建议必须包含**具体、可量化的触发条件**（如指数点位、PE/PB分位数、技术指标RSI/MACD数值、涨跌幅阈值等）。
        """
        
        # 获取当前日期用于市场分析
        today = datetime.now().strftime("%Y-%m-%d")
        
        # 获取投资目标
        investment_targets = self.get_investment_targets()
        
        # 构建用户提示 - 强调市场环境和减仓策略
        user_prompt = f"""
当前日期：{today}
      
{self.portfolio_manager.get_portfolio_text()}
        
{investment_targets}"""
        
        print('***************************************************')
        print(system_prompt)
        print('***************************************************')
        print(user_prompt)
        print('***************************************************')
        try:
            # 调用DeepSeek API
            response = self.client.chat.completions.create(
                model=self.settings['model'],
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ],
                temperature=self.settings['temperature'],
                response_format={"type": "json_object"}
            )
            
            # 解析响应
            json_response = response.choices[0].message.content
            plan = json.loads(json_response)
            
            print("✅ 成功获取DeepSeek操作计划, 正在保存...")
            # 保存操作计划
            with open(self.settings['plan_file'], 'w') as f:
                json.dump(plan, f, indent=4, ensure_ascii=False)
            
            return plan
        
        except Exception as e:
            print(f"❌ DeepSeek API调用失败: {str(e)}")
            return None

# ====================== 每日执行类 ======================
class DailyExecutor:
    def __init__(self, config_manager):
        self.config_manager = config_manager
        self.settings = config_manager.get_settings()
        self.deepseek_config = config_manager.get_deepseek_config()
        
        # 初始化DeepSeek客户端
        self.client = OpenAI(
            api_key=self.deepseek_config['api_key'],
            base_url=self.deepseek_config['base_url'] + "/v1"
        )
        
        self.portfolio_manager = PortfolioManager(self.settings)
        self.operation_plan = {}
    
    def load_operation_plan(self):
        """加载操作计划"""
        if os.path.exists(self.settings['plan_file']):
            try:
                with open(self.settings['plan_file'], 'r') as f:
                    return json.load(f)
            except:
                print("⚠️ 操作计划文件损坏")
        return None
    
    def get_deepseek_condition_evaluation(self, market_data, portfolio_summary, operation_plan):
        """使用DeepSeek API评估条件是否满足（基于持仓计划表和持仓信息）"""
        # 构建系统提示
        system_prompt = """
你是一位专业的量化交易分析师，负责根据持仓计划表和当前持仓信息分别判断每个基金操作是否触发。
请严格基于以下规则进行评估：
1. 请基于当前最新的市场数据进行分析
2. 只有在当前持仓信息和市场条件满足计划表中的触发条件时，并且当前持仓与目标持仓的差距时才标记为触发
3. 考虑操作优先级和时间窗口
4. 用户会提供部分市场行情数据，可作为触发条件参考，针对触发条件中需要且未提供的数据，需要自己从网络获取
5. 未明确触发条件可视为立即执行
6. 如果被触发，请根据用户传入的当前仓位信息与操作计划中的目标仓位信息配置适当的操作比例
7. 如果当前仓位信息与操作计划中包含的基金不同时，如下处理
  - 如果持仓信息中有的基金信息，操作计划不包含时，该基金返回的结果应该为未被触发，操作方向应该是维持
  - 如果操作计划中有的基金，持仓信息中不包含时，视为该基金目前持仓为0

返回的json文件中包含以下信息：
对于每一个基金，应包含
1. 基金代码
2. 基金名称
3. 条件是否被触发
4. 触发条件，如果被触发，请说明被触发的条件说明，如果没有触发则填写没被触发的原因。
5. 操作方向(加仓/减仓/维持)
        
JSON格式如下：
        {
            "funds": [
                    {
                        "fund_code": "基金代码",
                        "fund_name": "基金名称",
                        "triggered": true/false,
                        "condition": "被触发的具体条件",
                        "recommended_action": "建议的具体操作"
                    },
                    // 其他基金...
                ],
            "market_news": "current market"
        }
        """
        
        # 构建用户提示
        user_prompt = f"""
操作计划表摘要（JSON格式）：
{json.dumps(operation_plan, indent=2, ensure_ascii=False)}
        
当前持仓信息（JSON格式）：
{json.dumps(portfolio_summary, indent=2, ensure_ascii=False)}
另外附上如下市场信息作为参考：
上证指数点位：{market_data['上证指数']} 
沪深300点位：{market_data['沪深300']}
纳斯达克指数点位：{market_data['纳斯达克指数']}
上一交易日黄金价格：{market_data['黄金价格']}
中证消费指数：{market_data['中证消费指数']}
沪深300当前市盈率（PE）：{market_data['沪深300_PE']}
以上数据如某一项明显错误，则忽略该项"""
        print('***************************************************')
        print(system_prompt)
        print('***************************************************')
        print(user_prompt)
        print('***************************************************')
        try:
            # 调用DeepSeek API
            response = self.client.chat.completions.create(
                model=self.settings['model'],
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ],
                temperature=0.1,  # 使用低温确保判断准确
                response_format={"type": "json_object"}
            )
            
            # 解析响应
            json_response = response.choices[0].message.content
            evaluation = json.loads(json_response)
            return evaluation
        
        except Exception as e:
            print(f"❌ DeepSeek条件评估失败: {str(e)}")
            return {
                "funds": [
                    {
                        "fund_code": "", 
                        "fund_name": "",
                        "triggered": False,
                        "condition": "",
                        "recommended_action": ""
                    }
                ],
                "market_news": "current market"
            }
    
    def get_current_market_data(self):
        """获取当前市场数据 - 使用金融API"""
        market_data = {
            "日期": datetime.now().strftime("%Y-%m-%d"),
            "上证指数": None,
            "沪深300": None,
            "中证消费指数": None,
            "纳斯达克指数": None,
            "黄金价格": None,
            "美联储降息": 0,
            "沪深300_PE": None,
            "沪深300_PE分位数": None
        }
        
        try:
            # 尝试使用akshare
            index_data = ak.stock_zh_index_spot_sina()
            hs300 = index_data[index_data['代码'] == 'sh000300']
            market_data['沪深300'] = hs300['最新价'].values[0]
            print(f"获取沪深300指数数据: {market_data['沪深300']}")
                
            # 获取上证指数数据
            sh_index = index_data[index_data['代码'] == 'sh000001']
            market_data['上证指数'] = sh_index['最新价'].values[0]
            print(f"从AKshare获取上证指数数据: {market_data['上证指数']}")
            
            # 尝试使用akshare
            try:
                index_global_hist_em_df = ak.index_global_hist_em(symbol="纳斯达克")
                if not index_global_hist_em_df:
                    market_data['纳斯达克指数'] = index_global_hist_em_df['最新价'].iloc[-1]
                    print(f"从AKshare获取纳斯达克指数数据: {market_data['纳斯达克指数']}")
                
                # 获取黄金ETF实时行情（黄金ETF）
                
                macro_china_au_report_df = ak.macro_china_au_report()
                last_au = macro_china_au_report_df[macro_china_au_report_df['商品'] == 'Au99.99'].iloc[-1]
                market_data['黄金价格'] = last_au['收盘价']
                print(f"从AKshare获取黄金价格: {market_data['黄金价格']}")
            except Exception as e:
                print(f"akshare 获取纳斯达克100数值异常: {str(e)}")

            #stock_zh_index_hist_csindex_df = ak.stock_zh_index_hist_csindex(symbol="000300") # 获取1000多条市盈率数据，但数据相对较老
            stock_zh_index_value_csindex_df = ak.stock_zh_index_value_csindex(symbol="000300") #  获取较新数据，但只有20条
            market_data['沪深300_PE'] = stock_zh_index_value_csindex_df.iloc[0]['市盈率1']

            #market_data['沪深300_PE分位数'] = round(70 + random.uniform(-5, 5), 2)
            
            # 模拟其他数据
            xf_index = index_data[index_data['代码'] == 'sh000932']
            market_data['中证消费指数'] = xf_index['最新价'].values[0]
            #market_data['美联储降息'] = 1 if datetime.now().month == 9 and datetime.now().day > 15 else 0
            
            return market_data
        
        except Exception as e:
            print(f"金融API调用失败: {str(e)}，使用模拟数据")
            return self.get_simulated_market_data()
    
    def get_simulated_market_data(self):
        """模拟市场数据（当API不可用时使用）"""
        # 使用日期作为随机因子，使数据每天变化但保持连续性
        day_factor = datetime.now().day
        
        return {
            "日期": datetime.now().strftime("%Y-%m-%d"),
            "上证指数": 0,
            "沪深300": 0,
            "中证消费指数": 0,
            "纳斯达克指数": 10,
            "黄金价格": 0,
            "沪深300_PE": 0,
            "沪深300_PE分位数": 0
        }
    
    def log_operations(self, report):
        """记录操作日志 - 详细记录所有操作"""
        log_entry = f"\n=== {report['date']} ===\n"
        
        # 添加市场数据摘要
        if report['market_data']:
            log_entry += "市场快照: "
            log_entry += f"上证指数={report['market_data'].get('上证指数', 'N/A')} | "
            log_entry += f"沪深300={report['market_data'].get('沪深300', 'N/A')} | "
            log_entry += f"纳指={report['market_data'].get('纳斯达克指数', 'N/A')}\n"
            
            # 添加PE估值信息
            if '沪深300_PE' in report['market_data']:
                log_entry += f"沪深300估值: PE={report['market_data']['沪深300_PE']} "
                log_entry += f"(分位数: {report['market_data']['沪深300_PE分位数']}%)\n"
        
        if report["actions"]:
            log_entry += "操作记录:\n"
            for action in report["actions"]:
                log_entry += (f"- [{action['fund_code']}] {action['fund_name']}: "
                            f"{action['action_type']} {action['step_percent']}% "
                            f"({action['current_percent']}% → {action['new_percent']}%)\n")
                log_entry += f"  触发条件: {action['trigger_condition']}\n"
                log_entry += f"  建议操作: {action['recommended_action']}\n"
                log_entry += f"  剩余调整: {action['remaining_adjustment']}%\n"
        else:
            log_entry += "今日无触发操作\n"
        
        # 添加总仓位建议
        total_plan = self.operation_plan.get("operation_plan", {}).get("total_position", {})
        if total_plan:
            # 计算当前总仓位
            current_total = sum(fund['持仓比例'] for fund in self.portfolio_manager.portfolio)
            target_total = total_plan.get('target', current_total)
            
            log_entry += f"\n💼 总仓位建议: {current_total:.1f}% → {target_total:.1f}%\n"
            log_entry += f"理由: {total_plan['reason']}\n"
            log_entry += f"步进比例: {total_plan.get('step_percent', 'N/A')}%\n"
        
        # 添加市场分析摘要
        market_analysis = self.operation_plan.get("operation_plan", {}).get("market_analysis", "")
        if market_analysis:
            log_entry += f"\n📈 市场分析摘要:\n{market_analysis[:300]}...\n"
        
        # 添加指数估值摘要
        index_valuation = self.operation_plan.get("operation_plan", {}).get("index_valuation", {})
        if index_valuation:
            log_entry += "\n📊 指数估值分析:\n"
            for index, data in index_valuation.items():
                log_entry += f"- {index}: PE={data.get('current_pe', 'N/A')} "
                log_entry += f"(分位数: {data.get('percentile', 'N/A')}%) "
                log_entry += f"→ {data.get('recommendation', 'N/A')}\n"
        
        with open(self.settings['log_file'], 'a') as f:
            f.write(log_entry)
    
    def generate_daily_report(self):
        """生成每日操作报告 - 基于实际持仓和计划表"""
        # 加载操作计划
        self.operation_plan = self.load_operation_plan()
        if not self.operation_plan:
            print("❌ 无法生成报告：缺少操作计划")
            return False
        
        today = datetime.now().strftime("%Y-%m-%d")
        report = {
            "date": today,
            "actions": [],
            "market_data": self.get_current_market_data(),
            "portfolio_summary": self.portfolio_manager.get_portfolio_summary()
        }
        unexe_report = {
            "date": today,
            "actions": [],
        }
        fund_op_plan = self.operation_plan.get("operation_plan", {}).get("funds", [])
        evaluation = self.get_deepseek_condition_evaluation(report['market_data'], report['portfolio_summary'], fund_op_plan)
        #print({json.dumps(evaluation, indent=4, ensure_ascii=False)})
        for fund in evaluation.get("funds", []):
            print(f"基金名称: {fund['fund_name']}, 是否触发: {fund['triggered']}, 原因: {fund['condition']}")
            if fund.get("triggered", False):
                current_percent = self.portfolio_manager.get_fund_current_percent(fund['fund_code'])
                target_percent = next((fund_plan['target_percent'] for fund_plan in fund_op_plan if fund_plan['fund_code'] == fund['fund_code']), None)
                step_percent = next((fund_plan['step_percent'] for fund_plan in fund_op_plan if fund_plan['fund_code'] == fund['fund_code']), None)
                print(f"基金： {fund['fund_name']},步进：{step_percent}, 目标：{target_percent}")
                #target_percent = fund.get('target_percent', current_percent)
                # 计算剩余调整比例
                if fund['recommended_action'] in ["加仓", "建仓"]:
                    remaining = max(0, target_percent - current_percent)
                else:  # 减仓
                    remaining = max(0, current_percent - target_percent)
                
                # 确定实际调整比例
                actual_step = min(step_percent, remaining)
                
                # 只有实际调整比例大于0时才记录操作
                if actual_step > 0:
                    # 计算新持仓比例（仅用于显示，不实际修改）
                    if fund['recommended_action'] in ["加仓", "建仓"]:
                        new_percent = current_percent + actual_step
                    else:  # 减仓
                        new_percent = current_percent - actual_step
                    
                    report["actions"].append({
                        "fund_code": fund["fund_code"],
                        "fund_name": fund["fund_name"],
                        "action_type": fund["recommended_action"],
                        "step_percent": actual_step,
                        "trigger_condition": fund["condition"],
                        "recommended_action": fund["recommended_action"],
                        "remaining_adjustment": remaining - actual_step,
                        "current_percent": current_percent,
                        "new_percent": new_percent
                    })
            else:
                unexe_report["actions"].append({
                        "fund_code": fund["fund_code"],
                        "fund_name": fund["fund_name"],
                        "trigger_condition": fund["condition"]
                    })

			
        # 记录日志
        self.log_operations(report)
        
        # 打印报告
        self.print_report(report)
        return True
    
    def print_report(self, report):
        """打印操作报告 - 更详细的输出"""
        print(f"\n{'='*60}")
        print(f"📅 每日操作报告 - {report['date']}")
        
        # 打印市场数据
        if report['market_data']:
            print(f"📊 市场快照: 上证指数={report['market_data'].get('上证指数', 'N/A')} | "
                f"沪深300={report['market_data'].get('沪深300', 'N/A')} | "
                f"纳指={report['market_data'].get('纳斯达克指数', 'N/A')}")
            
            # 打印PE估值信息
            if '沪深300_PE' in report['market_data']:
                print(f"📈 沪深300估值: PE={report['market_data']['沪深300_PE']} "
                    f"(分位数: {report['market_data']['沪深300_PE分位数']}%)")
        
        # 打印总仓位建议
        total_plan = self.operation_plan.get("operation_plan", {}).get("total_position", {})
        if total_plan:
            # 计算当前总仓位
            current_total = sum(fund['持仓比例'] for fund in self.portfolio_manager.portfolio)
            target_total = total_plan.get('target', current_total)
            
            print(f"\n💼 总仓位建议: {current_total:.1f}% → {target_total:.1f}%")
            print(f"理由: {total_plan['reason']}")
            print(f"步进比例: {total_plan.get('step_percent', 'N/A')}%")
        
        # 打印指数估值建议
        index_valuation = self.operation_plan.get("operation_plan", {}).get("index_valuation", {})
        if index_valuation:
            print("\n📊 指数估值建议:")
            for index, data in index_valuation.items():
                print(f"- {index}: PE={data.get('current_pe', 'N/A')} "
                    f"(分位数: {data.get('percentile', 'N/A')}%) → {data.get('recommendation', 'N/A')}")
        
        if report["actions"]:
            print("\n🔔 触发操作建议:")
            for action in report["actions"]:
                print(f"- [{action['fund_code']}] {action['fund_name']}: "
                    f"{action['action_type']} {action['step_percent']}% "
                    f"({action['current_percent']}% → {action['new_percent']}%)")
                print(f"  触发条件: {action['trigger_condition']}")
                print(f"  建议操作: {action['recommended_action']}")
                print(f"  剩余调整: {action['remaining_adjustment']}%")
        else:
            print("\n🟢 今日无触发操作")
        
        # 特殊事件提醒
        if datetime.now().month == 9 and datetime.now().day > 15:
            print("\n📢 事件提示: 美联储议息会议进行中，关注降息动向")
        if datetime.now().month == 11 and datetime.now().day > 10:
            print("\n📢 事件提示: 医疗集采政策陆续落地，警惕波动风险")
        
        print(f"\n操作日志已更新: {self.settings['log_file']}")
        print(f"{'='*60}")

# ====================== 定时任务 ======================
def plan_update_job():
    """更新操作计划 """
    print("\n⏰ 正在更新操作计划...")
    config_manager = ConfigManager()
    plan_updater = PlanUpdater(config_manager)
    plan = plan_updater.get_deepseek_operation_plan()

    if plan:
        print("✅ 操作计划更新完成")
        
        # 打印新计划摘要
        if "operation_plan" in plan:
            op_plan = plan["operation_plan"]
            print(f"\n📋 新计划摘要:")
            
            # 总仓位建议
            if "total_position" in op_plan:
                total = op_plan["total_position"]
                print(f"总仓位: {total.get('current', 'N/A')}% → {total.get('target', 'N/A')}%")
            
            # 基金操作
            if "funds" in op_plan:
                print("基金操作建议:")
                for fund in op_plan["funds"]:
                    action = fund.get("action", "")
                    print(f"- [{fund.get('fund_code', '')}] {action} {fund.get('current_percent', '')}% → {fund.get('target_percent', '')}%")
            
            # 市场分析摘要
            if "market_analysis" in op_plan:
                print(f"\n📈 市场分析摘要: {op_plan['market_analysis'][:100]}...")
    else:
        print("❌ 操作计划更新失败")

def daily_operation_check():
    """每日操作检查"""
    print("\n⏰ 正在执行每日操作检查...")
    config_manager = ConfigManager()
    daily_executor = DailyExecutor(config_manager)
    daily_executor.generate_daily_report()

# ====================== 主程序 ======================
def main():
    print("📊 持仓管理系统 v10.0 (指数估值驱动)")
    
    # 初始化配置
    config_manager = ConfigManager()
    settings = config_manager.get_settings()
    """
    print(f"• 配置文件: {CONFIG_FILE}")
    print(f"• 持仓文件: {settings['portfolio_file']}")
    print(f"• 操作计划: {settings['plan_file']}")
    print(f"• 操作日志: {settings['log_file']}")
    print(f"• 投资目标: {settings['targets_file']}")
    print(f"• 使用模型: {settings['model']}")
    
    # 设置定时任务
    daily_time = settings['daily_check_time']
    
    # 每天执行操作检查
    schedule.every().day.at(daily_time).do(daily_operation_check)
    
    # 每周一检查是否需要更新计划（实际更新频率为每两周一次）
    schedule.every().monday.at("09:00").do(plan_update_job)
    
    print("\n定时任务设置:")
    print(f"- 每周一 09:00: 检查操作计划更新（每两周更新一次）")
    print(f"- 每天 {daily_time}: 执行操作检查")
    print("\n金融数据API使用说明:")
    print("- 系统使用Alpha Vantage和Yahoo Finance获取实时市场数据")
    print("- 如需更全面的数据，建议使用以下收费API:")
    print("  • Wind金融终端 (专业机构使用)")
    print("  • Tushare Pro (tushare.pro)")
    print("  • JoinQuant (量化交易平台)")
    print("  • RiceQuant (量化交易平台)")
    print("\n等待执行中... (Ctrl+C退出)")
    # 首次运行更新计划
    """
    plan_update_job()
#    daily_operation_check()
    """
    try:
        while True:
            schedule.run_pending()
            time.sleep(60)
    except KeyboardInterrupt:
        print("\n程序已退出")
    """

if __name__ == "__main__":
    main()
